<script setup>
import { getUserAPI, deleteUserAPI, createUserAPI, updateUserAPI } from '@/api'
import { onMounted, reactive, useTemplateRef } from 'vue'

// 获取用户数据
const userData = ref(null)
const total = ref(0)
const params = reactive({
  currentPage: 1,
  pageSize: 10,
  keyword: '',
})
const getUserData = async params => {
  const res = await getUserAPI(params)
  userData.value = res.data.list
  total.value = res.data.total
}

// 搜索功能
const handleSearch = () => {
  getUserData(params)
}

// 分页功能
const currentPage = ref(1)
const pageSize = ref(10)
const handleSizeChange = val => {
  params.pageSize = val
  getUserData(params)
}
const handleCurrentChange = val => {
  params.currentPage = val
  getUserData(params)
}

// 用户功能
const dialogFormVisible = ref(false)
const action = ref('add')
const form = ref({
  name: '',
  age: '',
  sex: '',
  address: '',
  birth: '',
})
const rules = reactive({
  name: [{ required: true, message: '姓名是必填项', trigger: 'blur' }],
  age: [
    { required: true, message: '年龄是必填项', trigger: 'blur' },
    {
      type: 'number',
      message: '年龄必须为数字值',
      trigger: 'blur',
    },
  ],
  sex: [{ required: true, message: '性别是必选项', trigger: 'change' }],
  birth: [{ required: true, message: '出生日期是必选项' }],
  address: [{ required: true, message: '地址是必填项', trigger: 'blur' }],
})
// 点击新增用户按钮
const handleAdd = () => {
  action.value = 'add'
  dialogFormVisible.value = true
}
// 点击编辑用户按钮
const handleEdit = row => {
  action.value = 'edit'
  dialogFormVisible.value = true
  nextTick(() => {
    form.value = { ...row }
  })
}
// 点击删除用户按钮
const handleDelete = row => {
  ElMessageBox.confirm('你确定要删除该用户吗?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deleteUserAPI({ id: row.id })
    getUserData(params)
  })
}

// 点击提交表单按钮
const formRef = useTemplateRef('formRef')
const submitForm = () => {
  if (!formRef.value) return
  formRef.value.validate(valid => {
    if (valid) {
      // 表单验证通过
      if (action.value === 'add') {
        // 添加用户
        createUserAPI(form.value).then(res => {
          if (res.code === 1) {
            dialogFormVisible.value = false
            getUserData(params)
            formRef.value.resetFields()
            ElMessage.success(res.msg)
          }
        })
      } else if (action.value === 'edit') {
        // 编辑用户
        updateUserAPI(form.value).then(res => {
          if (res.code === 1) {
            dialogFormVisible.value = false
            getUserData(params)
            formRef.value.resetFields()
            ElMessage.success(res.msg)
          }
        })
      }
    }
  })
}

// 点击取消按钮
const handleCancel = () => {
  dialogFormVisible.value = false
  action.value === 'edit' && formRef.value.resetFields()
}

// 计算年龄
const caculateAge = birthDate => {
  // 获取当前日期
  const today = new Date()
  // 获取出生日期
  const birth = new Date(birthDate)
  // 计算年龄
  const age = today.getFullYear() - birth.getFullYear()
  // 如果今年的生日还未到达，减去一年
  if (
    today.getMonth() < birth.getMonth() ||
    (today.getMonth() === birth.getMonth() && today.getDate() < birth.getDate())
  ) {
    age--
  }
  // 返回年龄
  return age
}
const handleBirthChange = value => {
  form.value.age = caculateAge(value)
}

onMounted(() => {
  getUserData(params)
})
</script>

<template>
  <div class="container">
    <div class="header">
      <el-button type="primary" @click="handleAdd">+ 新增用户</el-button>
      <el-form :inline="true">
        <el-form-item>
          <el-input
            placeholder="请输入搜索内容"
            v-model="params.keyword"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table :data="userData" style="width: 100%">
        <el-table-column prop="id" label="Id" width="120" />
        <el-table-column prop="name" label="Name" width="120" />
        <el-table-column prop="age" label="Age" width="120" />
        <el-table-column prop="sex" label="Sex" width="120">
          <template #default="scope">
            {{ scope.row.sex === '1' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="Address" width="300" />
        <el-table-column prop="birth" label="Birth" width="120" />
        <el-table-column label="Operations" min-width="120">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :disabled="false"
        :background="false"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增or编辑用户对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="action == 'add' ? '新增用户' : '编辑用户'"
      width="35%"
    >
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="form.name"
            autocomplete="off"
            placeholder="请输入姓名"
          />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input
            v-model.number="form.age"
            autocomplete="off"
            placeholder="请输入年龄"
          />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option label="男" value="1" />
            <el-option label="女" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
            v-model="form.address"
            autocomplete="off"
            placeholder="请输入地址"
          />
        </el-form-item>
        <el-form-item label="生日" prop="birth">
          <el-date-picker
            v-model="form.birth"
            type="date"
            placeholder="请选择"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleBirthChange"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="submitForm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.container {
  height: 100%;
  padding-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
